package com.pirestupppai.ui.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.VideoView;

import com.pirestupppai.R;
import com.pirestupppai.base.BaseActivity;
import com.pirestupppai.common.Constant;
import com.pirestupppai.utils.SharedPreferenceUtil;
import com.pirestupppai.utils.Utils;
import com.pirestupppai.widgets.dialog.CountDownDialog;
import com.yixia.videoeditor.adapter.UtilityAdapter;

import java.io.File;

import butterknife.BindView;
import mabeijianxi.camera.MediaRecorderBase;
import mabeijianxi.camera.MediaRecorderNative;
import mabeijianxi.camera.MediaRecorderSystem;
import mabeijianxi.camera.VCamera;
import mabeijianxi.camera.model.AutoVBRMode;
import mabeijianxi.camera.model.MediaObject;
import mabeijianxi.camera.model.MediaRecorderConfig;
import mabeijianxi.camera.util.FileUtils;
import mabeijianxi.camera.views.RecordProgressView;

import static com.pirestupppai.R.id.record_layout;

/**
 * author: xiaoluo
 * date: 2017/5/16 16:03
 */
public class VideoTuttiActivity extends BaseActivity implements
        MediaRecorderBase.OnErrorListener, MediaRecorderBase.OnPreparedListener,
        MediaRecorderBase.OnEncodeListener {

    private final static String TAG = VideoTuttiActivity.class.getSimpleName();
    private static final int HANDLE_INVALIDATE_PROGRESS = 0; // 刷新进度条
    private static final int HANDLE_STOP_RECORD = 1;         // 延迟拍摄停止
    private static final int WIDTH_VIDEO = 480;

    @BindView(R.id.parent_layout)
    RelativeLayout parentLayout;
    @BindView(R.id.origin_video)
    VideoView originVideo;
    @BindView(R.id.record_preview)
    SurfaceView surfaceView;
    @BindView(R.id.video_layout)
    RelativeLayout videoLayout;
    @BindView(record_layout)
    RelativeLayout recordLayout;
    @BindView(R.id.bottom_bar)
    RelativeLayout bottomBar;
    @BindView(R.id.record_progress)
    RecordProgressView recordProgress;
    @BindView(R.id.record_btn)
    ImageView recordBtn;
    @BindView(R.id.camera_btn)
    ImageView cameraBtn;
    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.record_next)
    ImageView nextBtn;
    @BindView(R.id.scroll_filter_linear)
    LinearLayout filterLayout;

    private String mVideoPath;
    private MediaRecorderBase mMediaRecorder;
    private MediaObject mMediaObject;
    private boolean isRecording = false;
    private volatile boolean isReleased = false;
    private int mMaxTime;
    private boolean isBegin = true;
    private int mCurrentTime = 0;
    private boolean isFirstEnterVideo = true;
    private CountDownDialog mCountDownDialog;

    private Integer[] mFilterResourceIds = {R.drawable.filter_tone_curve,R.drawable.filter_lookup_amatorka,
            R.drawable.filter_contrast, R.drawable.filter_monochrome, R.drawable.filter_levels_min,
            R.drawable.filter_grayscale, R.drawable.filter_vignette, R.drawable.filter_lookup_amatorka};

    @Override
    protected Context getActivityContext() {
        return this;
    }

    @Override
    protected int loadParentLayout() {
        return R.layout.activity_video_tutti;
    }

    @Override
    protected void initViews() {

        mVideoPath = getIntent().getStringExtra(Constant.IntentKey.VIDEO_PATH);
        mMaxTime = getIntent().getIntExtra(Constant.IntentKey.TIME, 3 * 1000);

//        mVideoPath = "android.resource://" + getPackageName() + "/" + R.raw.aa;
        mMaxTime = 14652;

        if (!TextUtils.isEmpty(mVideoPath)) {
            originVideo.setVideoPath(mVideoPath);
        }

        // 配置录制参数
        initConfig();
        // 防止锁屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        recordProgress.setMaxDuration(mMaxTime);
        recordProgress.setMinTime(0);

        // 滑动滤镜视图
        filterLayout.removeAllViews();
        for (int i = 0; i < 8; i++) {
            ImageView mImage = new ImageView(mContext);
            mImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    Utils.dpToPx(mContext, 60), Utils.dpToPx(mContext, 60));
            lp.setMargins(0, 0, Utils.dpToPx(mContext, 10), 0);
            mImage.setLayoutParams(lp);

            mImage.setBackgroundResource(mFilterResourceIds[i]);
            filterLayout.addView(mImage);
        }

        isFirstEnterVideo = SharedPreferenceUtil.getSp().getBoolean(Constant.SPKey.IS_FIRST_VIDEO, true);

    }

    private void initConfig() {
        MediaRecorderConfig config = new MediaRecorderConfig.Buidler()
//                        .doH264Compress(new AutoVBRMode()
//                        .setVelocity(BaseMediaBitrateConfig.Velocity.ULTRAFAST)
//                        )
                .setMediaBitrateConfig(new AutoVBRMode()
//                        .setVelocity(BaseMediaBitrateConfig.Velocity.ULTRAFAST)
                )
                .smallVideoWidth(WIDTH_VIDEO)
                .smallVideoHeight(WIDTH_VIDEO)
                .recordTimeMax(mMaxTime)
                .maxFrameRate(20)
                .captureThumbnailsTime(1)
                .recordTimeMin(0)
                .build();

        MediaRecorderBase.MAX_FRAME_RATE = config.getMaxFrameRate();
        MediaRecorderBase.MIN_FRAME_RATE = config.getMinFrameRate();
        MediaRecorderBase.SMALL_VIDEO_HEIGHT = config.getSmallVideoHeight();
        MediaRecorderBase.SMALL_VIDEO_WIDTH = config.getSmallVideoWidth();
        MediaRecorderBase.mVideoBitrate = config.getVideoBitrate();
        MediaRecorderBase.mediaRecorderConfig = config.getMediaBitrateConfig();
        MediaRecorderBase.compressConfig = config.getCompressConfig();
        MediaRecorderBase.CAPTURE_THUMBNAILS_TIME = config.getCaptureThumbnailsTime();
        MediaRecorderBase.doH264Compress = config.isDoH264Compress();
    }

    @Override
    protected void initListeners() {
        originVideo.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Utils.showToast("Error:" + what);
                finish();
                return false;
            }
        });

        originVideo.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                originVideo.start();
            }
        });

        originVideo.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                originVideo.start();
            }
        });

        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mMediaObject != null) {
                    mMediaObject.delete();
                }
                finish();
            }
        });

        cameraBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mMediaRecorder != null) {
                    mMediaRecorder.switchCamera();
                }
            }
        });

        nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMediaRecorder.startEncoding();
            }
        });

        recordBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mMediaRecorder == null) {
                    return;
                }



                if (!isRecording) {
                    // 检测是否手动对焦
                    // 判断是否已经超时
                    if (mMediaObject.getDuration() >= mMaxTime) {
                        return;
                    }

                    if (isBegin) {
                        if (isFirstEnterVideo) {
                            Utils.showToast("配戴耳机效果更佳~");
                            SharedPreferences.Editor editor = SharedPreferenceUtil.getEditor();
                            editor.putBoolean(Constant.SPKey.IS_FIRST_VIDEO, false);
                            editor.apply();
                        }
//
                        isBegin = false;
                        mCountDownDialog = new CountDownDialog(mContext, new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                originVideo.seekTo(mCurrentTime);
                                startRecord();
                            }
                        });
                        mCountDownDialog.show();
                    } else {
                        originVideo.start();
                        startRecord();
                    }



                } else {
                    mCurrentTime = originVideo.getCurrentPosition();
                    originVideo.pause();
                    stopRecord();


                    // 检测是否已经完成
                    if (mMediaObject.getDuration() >= mMaxTime) {
                        mMediaRecorder.startEncoding();
                    }
                }
            }
        });
    }

    /**
     * 初始化拍摄SDK
     */
    private void initMediaRecorder() {
        mMediaRecorder = new MediaRecorderNative();

        mMediaRecorder.setOnErrorListener(this);
        mMediaRecorder.setOnEncodeListener(this);
        mMediaRecorder.setOnPreparedListener(this);

        File f = new File(VCamera.getVideoCachePath());
        if (!FileUtils.checkFile(f)) {
            f.mkdirs();
        }
        String key = String.valueOf(System.currentTimeMillis());
        mMediaObject = mMediaRecorder.setOutputDirectory(key,
                VCamera.getVideoCachePath() + key);
        mMediaRecorder.setSurfaceHolder(surfaceView.getHolder());
        mMediaRecorder.prepare();
    }

    /**
     * 开始录制
     */
    private void startRecord() {

        isBegin = false;
        Log.d(TAG, "startRecord");
        if (mMediaRecorder != null) {

            MediaObject.MediaPart part = mMediaRecorder.startRecord();
            if (part == null) {
                return;
            }

            // 如果使用MediaRecorderSystem，不能在中途切换前后摄像头，否则有问题
            if (mMediaRecorder instanceof MediaRecorderSystem) {
                cameraBtn.setVisibility(View.GONE);
            }
            recordProgress.setData(mMediaObject);
        }

        isRecording = true;
        recordBtn.setImageResource(R.drawable.record_yellow);


        if (mHandler != null) {
            mHandler.removeMessages(HANDLE_INVALIDATE_PROGRESS);
            mHandler.sendEmptyMessage(HANDLE_INVALIDATE_PROGRESS);

            mHandler.removeMessages(HANDLE_STOP_RECORD);
//            mHandler.sendEmptyMessageDelayed(HANDLE_STOP_RECORD,
//                    RECORD_MAX_TIME - mMediaObject.getDuration());
        }
        cameraBtn.setVisibility(View.GONE);
        nextBtn.setVisibility(View.GONE);
    }

    /**
     * 停止录制
     */
    private void stopRecord() {
        Log.d(TAG, "stopRecord");
//        originVideo.pause();
        mCurrentTime = originVideo.getCurrentPosition();
        isRecording = false;
        recordBtn.setImageResource(R.drawable.record_gray);

        if (mMediaRecorder != null) {
            mMediaRecorder.stopRecord();
        }

        cameraBtn.setVisibility(View.VISIBLE);
        if (mMediaObject.getDuration() < mMaxTime) {
            nextBtn.setVisibility(View.GONE);
        } else {
            nextBtn.setVisibility(View.GONE);
        }

        mHandler.removeMessages(HANDLE_STOP_RECORD);
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLE_INVALIDATE_PROGRESS:
                    if (mMediaRecorder != null && !isFinishing()) {
                        if (mMediaObject != null && mMediaObject.getMedaParts() != null && mMediaObject.getDuration() >= mMaxTime) {
                            stopRecord();
                            nextBtn.performClick();
                            return;
                        }
                        if (recordProgress != null)
                            recordProgress.invalidate();
                        // if (mPressedStatus)
                        // titleText.setText(String.format("%.1f",
                        // mMediaRecorder.getDuration() / 1000F));
                        if (isRecording)
                            sendEmptyMessageDelayed(0, 30);
                    }
                    break;
            }
        }
    };


    @Override
    protected void initLogic() {

    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onPrepared() {
        initSurfaceView();
    }

    private void initSurfaceView() {
        RelativeLayout.LayoutParams bottomParams = (RelativeLayout.LayoutParams) bottomBar.getLayoutParams();
        bottomParams.width = Constant.WIDTH_OF_SCREEN;
        bottomParams.height = Constant.HEIGHT_OF_SCREEN - Constant.WIDTH_OF_SCREEN - (int) getResources().getDimension(R.dimen.titlebar_height) - Constant.HEIGHT_OF_STATUSBAR;
        bottomBar.setLayoutParams(bottomParams);

        RelativeLayout.LayoutParams videoParams = (RelativeLayout.LayoutParams) originVideo.getLayoutParams();
        videoParams.width = Constant.WIDTH_OF_SCREEN;
        videoParams.height = Constant.WIDTH_OF_SCREEN;
        videoParams.leftMargin = -Constant.WIDTH_OF_SCREEN / 4;
        videoParams.rightMargin = -Constant.WIDTH_OF_SCREEN / 4;
        originVideo.setLayoutParams(videoParams);

        RelativeLayout.LayoutParams surfaceParams = (RelativeLayout.LayoutParams) surfaceView.getLayoutParams();
        surfaceParams.width = Constant.WIDTH_OF_SCREEN;
        surfaceParams.height = (int) (Constant.WIDTH_OF_SCREEN * ((MediaRecorderBase.mSupportedPreviewWidth * 1.0f) / MediaRecorderBase.SMALL_VIDEO_WIDTH));
        surfaceParams.rightMargin = -Constant.WIDTH_OF_SCREEN / 2;
        surfaceView.setLayoutParams(surfaceParams);
        surfaceView.setPadding(-Utils.dpToPx(mContext, Constant.WIDTH_OF_SCREEN / 2), 0, 0, 0);

        RelativeLayout.LayoutParams recordParams = (RelativeLayout.LayoutParams) recordLayout.getLayoutParams();
        recordParams.width = Constant.WIDTH_OF_SCREEN / 2;
        recordParams.height = (int) (Constant.WIDTH_OF_SCREEN * ((MediaRecorderBase.mSupportedPreviewWidth * 1.0f) / MediaRecorderBase.SMALL_VIDEO_WIDTH));
        recordLayout.setLayoutParams(recordParams);

        RelativeLayout.LayoutParams originParams = (RelativeLayout.LayoutParams) videoLayout.getLayoutParams();
        originParams.width = Constant.WIDTH_OF_SCREEN / 2;
        originParams.height = Constant.WIDTH_OF_SCREEN;
        videoLayout.setLayoutParams(originParams);

        surfaceView.setZOrderOnTop(false);
        surfaceView.setZOrderMediaOverlay(false);


    }

    @Override
    public void onVideoError(int what, int extra) {

    }

    @Override
    public void onAudioError(int what, String message) {

    }

    @Override
    public void onEncodeStart() {
        Utils.showToast("请稍侯...");
    }

    @Override
    public void onEncodeProgress(int progress) {

    }

    @Override
    public void onEncodeComplete() {
        Intent intent = new Intent(mContext, VideoPreviewActivity.class);
        Bundle bundle = new Bundle();
        if(MediaRecorderBase.compressConfig!=null){
            bundle.putString(Constant.IntentKey.VIDEO_PATH, mMediaObject.getOutputTempTranscodingVideoPath());
        }else {
            bundle.putString(Constant.IntentKey.VIDEO_PATH, mMediaObject.getOutputTempVideoPath());
        }
        bundle.putInt(Constant.IntentKey.RELEASE_TYPE, Constant.SELETC_TYPE_VIDEO_WORK);
        bundle.putString(Constant.IntentKey.VIDEO_IMG, mMediaObject.getOutputVideoThumbPath());
        intent.putExtras(bundle);
        startActivity(intent);
        finish();
    }

    @Override
    public void onEncodeError() {
        Utils.showToast("onEncodeError");
    }

    @Override
    public void onPause() {
        super.onPause();
        stopRecord();
        UtilityAdapter.freeFilterParser();
        if (!isReleased) {
            if (mMediaRecorder != null)
                mMediaRecorder.release();
        }
        isReleased = false;
    }

    @Override
    public void onResume() {
        super.onResume();
        UtilityAdapter.freeFilterParser();
        UtilityAdapter.initFilterParser();

        if (mMediaRecorder == null) {
            initMediaRecorder();
        } else {
            mMediaRecorder.prepare();
            recordProgress.setData(mMediaObject);
        }
    }
}